from typing import Dict, Any, Optional
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings
from app.services.ai_base import AIServiceProvider

class ServiceConfig(BaseModel):
    """单个AI服务配置基类"""
    api_key: str = ""
    enabled: bool = True

class OpenAIConfig(ServiceConfig):
    """OpenAI DALL-E配置"""
    base_url: str = "https://api.openai.com/v1"
    model: str = "dall-e-3"
    max_retries: int = 3

class StabilityAIConfig(ServiceConfig):
    """Stability AI配置"""
    base_url: str = "https://api.stability.ai/v1"
    engine: str = "stable-diffusion-xl-1024-v1-0"
    max_retries: int = 3

class GoogleVeo3Config(ServiceConfig):
    """Google Veo 3配置"""
    project_id: str = ""
    location: str = "us-central1"
    service_account_path: str = ""
    max_duration: int = 60
    default_resolution: str = "1280x720"
    default_fps: int = 24

class RunwayMLConfig(ServiceConfig):
    """Runway ML配置"""
    base_url: str = "https://api.runwayml.com/v1"
    model_name: str = "gen3a_turbo"
    max_duration: int = 10
    default_resolution: str = "1280x768"

class JimengAIConfig(ServiceConfig):
    """即梦AI配置"""
    base_url: str = "https://api.jimeng.ai"
    user_id: str = ""
    model_name: str = "jimeng-1.0"
    max_duration: int = 6
    default_resolution: str = "1280x720"

class AIServicesSettings(BaseSettings):
    """AI服务统一配置管理"""
    
    # 全局AI服务配置
    ai_default_provider: str = "jimeng_ai"
    ai_services_enabled: bool = True
    ai_request_timeout: int = 300
    ai_max_concurrent_requests: int = 10
    
    # OpenAI DALL-E配置
    openai_api_key: str = ""
    openai_base_url: str = "https://api.openai.com/v1"
    openai_model: str = "dall-e-3"
    openai_use_mock: bool = False
    openai_enabled: bool = True
    
    # Stability AI配置
    stability_ai_api_key: str = ""
    stability_ai_base_url: str = "https://api.stability.ai/v1"
    stability_ai_engine: str = "stable-diffusion-xl-1024-v1-0"
    stability_ai_use_mock: bool = False
    stability_ai_enabled: bool = True
    
    # Google Veo 3配置
    google_veo3_api_key: str = ""
    google_veo3_project_id: str = ""
    google_veo3_location: str = "us-central1"
    google_veo3_service_account_path: str = ""
    google_veo3_max_duration: int = 60
    google_veo3_use_mock: bool = False
    google_veo3_enabled: bool = True
    
    # Runway ML配置
    runway_ml_api_key: str = ""
    runway_ml_model_name: str = "gen3a_turbo"
    runway_ml_max_duration: int = 10
    runway_ml_use_mock: bool = False
    runway_ml_enabled: bool = True
    
    # 即梦AI配置
    jimeng_ai_api_key: str = ""
    jimeng_ai_user_id: str = ""
    jimeng_ai_model_name: str = "jimeng-1.0"
    jimeng_ai_max_duration: int = 6
    jimeng_ai_use_mock: bool = False
    jimeng_ai_enabled: bool = True
    

    class Config:
        from pathlib import Path
        backend_dir = Path(__file__).resolve().parent.parent.parent
        env_file = str(backend_dir / ".env")
        env_prefix = ""
        case_sensitive = False
        extra = "ignore"  # 忽略额外的字段

class AIServicesConfigManager:
    """AI服务配置管理器"""
    
    def __init__(self):
        self.settings = AIServicesSettings()
    
    def get_service_config(self, provider: AIServiceProvider) -> Dict[str, Any]:
        """获取指定服务商的配置"""
        config_map = {
            AIServiceProvider.OPENAI_DALLE: self._get_openai_config,
            AIServiceProvider.STABILITY_AI: self._get_stability_ai_config,
            AIServiceProvider.GOOGLE_VEO3: self._get_google_veo3_config,
            AIServiceProvider.RUNWAY_ML: self._get_runway_ml_config,
            AIServiceProvider.JIMENG_AI: self._get_jimeng_ai_config,
        }
        
        config_func = config_map.get(provider)
        if not config_func:
            raise ValueError(f"不支持的AI服务提供商: {provider}")
        
        return config_func()
    
    def _get_openai_config(self) -> Dict[str, Any]:
        """获取OpenAI配置"""
        return {
            "api_key": self.settings.openai_api_key,
            "base_url": self.settings.openai_base_url,
            "model": self.settings.openai_model,
            "enabled": self.settings.openai_enabled,
            "max_retries": 3,
            "timeout": self.settings.ai_request_timeout
        }
    
    def _get_stability_ai_config(self) -> Dict[str, Any]:
        """获取Stability AI配置"""
        return {
            "api_key": self.settings.stability_ai_api_key,
            "base_url": self.settings.stability_ai_base_url,
            "engine": self.settings.stability_ai_engine,
            "enabled": self.settings.stability_ai_enabled,
            "max_retries": 3,
            "timeout": self.settings.ai_request_timeout
        }
    
    def _get_google_veo3_config(self) -> Dict[str, Any]:
        """获取Google Veo 3配置"""
        return {
            "api_key": self.settings.google_veo3_api_key,
            "project_id": self.settings.google_veo3_project_id,
            "location": self.settings.google_veo3_location,
            "service_account_path": self.settings.google_veo3_service_account_path,
            "max_duration": self.settings.google_veo3_max_duration,
            "default_resolution": "1280x720",
            "default_fps": 24,
            "enabled": self.settings.google_veo3_enabled,
            "timeout": self.settings.ai_request_timeout
        }
    
    def _get_runway_ml_config(self) -> Dict[str, Any]:
        """获取Runway ML配置"""
        return {
            "api_key": self.settings.runway_ml_api_key,
            "model_name": self.settings.runway_ml_model_name,
            "max_duration": self.settings.runway_ml_max_duration,
            "default_resolution": "1280x768",
            "enabled": self.settings.runway_ml_enabled,
            "timeout": self.settings.ai_request_timeout
        }
    
    def _get_jimeng_ai_config(self) -> Dict[str, Any]:
        """获取即梦AI配置"""
        return {
            "api_key": self.settings.jimeng_ai_api_key,
            "user_id": self.settings.jimeng_ai_user_id,
            "model_name": self.settings.jimeng_ai_model_name,
            "max_duration": self.settings.jimeng_ai_max_duration,
            "default_resolution": "1280x720",
            "enabled": self.settings.jimeng_ai_enabled,
            "timeout": self.settings.ai_request_timeout
        }
    
    
    def get_all_configs(self) -> Dict[AIServiceProvider, Dict[str, Any]]:
        """获取所有服务配置"""
        configs = {}
        for provider in AIServiceProvider:
            try:
                configs[provider] = self.get_service_config(provider)
            except ValueError:
                # 跳过不支持的服务商
                continue
        return configs
    
    def get_enabled_services(self) -> Dict[AIServiceProvider, Dict[str, Any]]:
        """获取所有已启用的服务配置"""
        all_configs = self.get_all_configs()
        return {provider: config for provider, config in all_configs.items() if config.get("enabled", True)}
    
    def is_service_enabled(self, provider: AIServiceProvider) -> bool:
        """检查服务是否启用"""
        try:
            config = self.get_service_config(provider)
            return config.get("enabled", True)
        except ValueError:
            return False
    
    def validate_service_config(self, provider: AIServiceProvider) -> bool:
        """验证服务配置是否有效"""
        try:
            config = self.get_service_config(provider)
            
            # 检查必需的API密钥
            api_key = config.get("api_key", "")
            if not api_key or api_key.strip() == "":
                return False
            
            # 特殊验证规则
            if provider == AIServiceProvider.GOOGLE_VEO3:
                project_id = config.get("project_id", "")
                if not project_id or project_id.strip() == "":
                    return False
            
            if provider == AIServiceProvider.JIMENG_AI:
                user_id = config.get("user_id", "")
                if not user_id or user_id.strip() == "":
                    return False
            
            return True
            
        except ValueError:
            return False
    
    def get_service_status(self) -> Dict[str, Dict[str, Any]]:
        """获取所有服务状态概览"""
        status = {}
        for provider in AIServiceProvider:
            try:
                config = self.get_service_config(provider)
                status[provider.value] = {
                    "enabled": config.get("enabled", True),
                    "config_valid": self.validate_service_config(provider),
                    "api_key_configured": bool(config.get("api_key", "").strip())
                }
            except ValueError:
                status[provider.value] = {
                    "enabled": False,
                    "config_valid": False,
                    "api_key_configured": False,
                    "error": "不支持的服务商"
                }
        return status

# 全局配置管理器实例
ai_services_config = AIServicesConfigManager()

# 兼容性函数：提供简单的配置获取接口
def get_ai_service_config(provider: AIServiceProvider) -> Dict[str, Any]:
    """获取AI服务配置（兼容性接口）"""
    return ai_services_config.get_service_config(provider)